package cn.itsource.hrm.service.impl;

import cn.hutool.core.util.ZipUtil;
import cn.itsource.hrm.Client.CourseClient;
import cn.itsource.hrm.PageClient;
import cn.itsource.hrm.client.FileClient;
import cn.itsource.hrm.client.RedisClient;
import cn.itsource.hrm.config.RabbitmqConfig;
import cn.itsource.hrm.domain.CourseType;
import cn.itsource.hrm.mapper.CourseMarketMapper;
import cn.itsource.hrm.mapper.CourseTypeMapper;
import cn.itsource.hrm.service.ICourseTypeService;
import cn.itsource.util.AjaxResult;
import cn.itsource.util.RabbitmqConst;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.fileupload.FileItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程目录 服务实现类
 * </p>
 *
 * @author chenyuqi
 * @since 2020-05-21
 */
@Service
public class CourseTypeServiceImpl extends ServiceImpl<CourseTypeMapper, CourseType> implements ICourseTypeService {
    private  String COURSE_TYPE_KEY = "COURSE:COURSETYPES:TREE";
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private CourseClient courseClient;
    @Autowired
    private FileClient fileClient;
    @Autowired
    private PageClient pageClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    private Logger logger = LoggerFactory.getLogger(CourseTypeServiceImpl.class);

    /**
     * 课程首页静态化
     */
    @Override
    public void staticHomePage() throws Exception{
        //上传模板文件到fastdfs中，获取模板文件的fileId
        //1home.vm和template目录进行打包，打包成一个压缩文件
        String classPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        String srcPath = classPath+"templates";
        String zipPath = classPath+"static.zip";
        ZipUtil.zip(srcPath, zipPath);
        //2将压缩文件进行上传 feign的文件上传
        //将file文件转换为MutipartFile
        File f = new File(zipPath);
        FileItem fileItem = new DiskFileItem("file", Files.probeContentType(f.toPath()), false, f.getName(), (int) f.length(), f.getParentFile());
        InputStream in = new FileInputStream(f);
        OutputStream os = fileItem.getOutputStream();
        IOUtils.copy(in, os);
        MultipartFile multipartFile = new CommonsMultipartFile(fileItem);


        AjaxResult result = fileClient.upload(multipartFile);
        System.out.println("模板fileId="+result.getResultObj());

        //组装模板中的数据
        Map<String,Object> data = new HashMap<>();
        data.put("courseTypes",loadTypeTree());


        //调用页面静态化服务的接口实现页面静态化，获取静态化文件的filId
        AjaxResult ajaxResult = pageClient.staticPage((String) result.getResultObj(), data);
        String staticPageFileId = (String)ajaxResult.getResultObj();

        System.out.println("页面静态化文件的fileId="+staticPageFileId);
        //将fileId作为消息发送到mq中去
        rabbitTemplate.convertAndSend(RabbitmqConst.PAGE_EXCHANGE_NAME,"page.course.home",staticPageFileId);

    }
    @Override
    public List<CourseType> loadTypeTree() {

        String courseTypesStr = redisClient.get(COURSE_TYPE_KEY);
        logger.debug("从缓存中查询");
        if (!StringUtils.isEmpty(courseTypesStr)) {
            List<CourseType> courseTypes = JSONArray.parseArray(courseTypesStr, CourseType.class);
            return courseTypes;
        }
        List<CourseType> courseTypes = loadRTypeTreeLoopMap();
        logger.debug("从数据库中查询");
        String courseTypeJSON = JSONArray.toJSONString(courseTypes);
        redisClient.set(COURSE_TYPE_KEY, courseTypeJSON);
        return courseTypes;
    }


    private List<CourseType> loadRTypeTreeLoopMap(){
        //1、查询所有的课程类型
        List<CourseType> courseTypeList = baseMapper.selectList(null);

        //2、创建一个容器存储所有的一级类型
        List<CourseType> firstCourseTypes = new ArrayList<>();

        //3、创建一个Map容器存储所有类型,key是类型的id，value为类型对象
        HashMap<Long, CourseType> courseTypeMap = new HashMap<>();
        for (CourseType courseType:courseTypeList) {
            courseTypeMap.put(courseType.getId(),courseType);
        }

        //4、遍历所有的课程类型，如果当前类型没有父类型，则放入到一级类型的集合中
        for (CourseType courseType:courseTypeList) {
            if (courseType.getPid()==0){
                firstCourseTypes.add(courseType);
            }else {//5、如果当前类型有父类型，则找到对应的父类型，添加父类型的 children中
                CourseType parentType = courseTypeMap.get(courseType.getPid());
                parentType.getChildren().add(courseType);
            }
        }
        return firstCourseTypes;
    }
}
